from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn
from sqlalchemy import text
from dotenv import load_dotenv
import traceback

# 加载环境变量
load_dotenv()

from config.database import engine, get_db
from models import Base
from routers import auth, books, user, admin

# 测试数据库连接
try:
    with engine.connect() as connection:
        connection.execute(text("SELECT 1"))
        print("✅ 数据库连接成功")
except Exception as e:
    print(f"❌ 数据库连接失败: {e}")
    print("请检查MySQL服务是否启动，数据库是否存在")

# 创建数据库表
try:
    Base.metadata.create_all(bind=engine)
    print("✅ 数据库表创建成功")
except Exception as e:
    print(f"❌ 数据库表创建失败: {e}")

app = FastAPI(
    title="图书管理系统 API",
    description="基于FastAPI的图书管理系统后端API",
    version="1.0.0"
)

# 添加全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    print(f"❌ 全局异常捕获: {str(exc)}")
    print(f"❌ 异常详情: {traceback.format_exc()}")
    return JSONResponse(
        status_code=500,
        content={"detail": f"服务器内部错误: {str(exc)}"}
    )

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(auth.router, prefix="/api/auth", tags=["认证"])
app.include_router(books.router, prefix="/api/books", tags=["图书"])
app.include_router(user.router, prefix="/api/user", tags=["用户"])
app.include_router(admin.router, prefix="/api/admin", tags=["管理员"])

@app.get("/")
async def root():
    return {"message": "图书管理系统 API", "version": "1.0.0"}

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)